package com.situ.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LastAcessTimeServlet
 */
@WebServlet("/LastAcessTimeServlet")
public class LastAccessTimeServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1.记录每次访问的时间，存放到Cookie里面，不管是不是第一次
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss");
		String time = simpleDateFormat.format(date);
		Cookie cookie = new Cookie("lastAccessTime", time);
		resp.addCookie(cookie);
		// 2.获取Cookie中的lastAccessTime，显示到页面上
		Cookie[] cookies = req.getCookies();
	    String lastAccessTime = "";
		if (cookies != null) {
			for (Cookie coo : cookies) {
				// 可能会有很多Cookie，但是我们只关心lastAccessTime这个Cookie
				// lastAccessTime=2020-02-24 02:17:39
				if ("lastAccessTime".equals(coo.getName())) {
				  lastAccessTime = coo.getValue();
				}
			}
		}
				
		// 3.在页面中显示,直接通过Response返回数据，不需要非得写一个jsp页面
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		if ("".equals(lastAccessTime)) {
			// println()是直接返回给浏览器显示
			writer.println("您是第一次访问");
		} else {
			writer.println("您上次访问的时间是：" + lastAccessTime);
		}
		writer.close();
	}
		


}

